﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CarBooker.Infrastructure.RepositoryFramework.Configuration;
using CarBooker.Infrastructure.DomainBase;
using System.Configuration;

namespace CarBooker.Infrastructure.RepositoryFramework
{
    public static class RepositoryFactory
    {
        //To enforce singletoon pattern
        //We came to the same point, where static object is instantiated!
        private static Dictionary<string, object> repositories = new Dictionary<string, object>();

        public static TRepository GetRepository<TRepository, TEntity>()
            where TRepository : class, IRepository<TEntity>
            where TEntity : EntityBase
        {
            TRepository repository = default(TRepository);
            string interfaceShortName = typeof(TRepository).Name;

            //see if the provider was already created and in the cache:
            if (!RepositoryFactory.repositories.ContainsKey(interfaceShortName))
            {
                //no, we need to create one: 
                RepositorySettings settings=
                (RepositorySettings)ConfigurationManager.GetSection(
                    RepositoryMappingConstants.RepositoryMappingsConfigurationSectionName);
                repository=
                    Activator.CreateInstance(
                    Type.GetType(settings.
                        RepositoryMappings[interfaceShortName].
                        RepositoryFullTypeName)) as TRepository;
                RepositoryFactory.repositories.Add(interfaceShortName,repository);
            }
            else
            {
                //The provider was in the cache!
                repository=
                (TRepository)RepositoryFactory.repositories[interfaceShortName];
            }
            return repository;
           }
    }
}
